/*
** env.c for env in /home/lingla_j/work/tutorat
** 
** Made by julien linglain
** Login   <lingla_j@epitech.net>
** 
** Started on  Mon Feb 20 17:18:27 2012 julien linglain
** Last update Sun Mar  4 19:14:51 2012 julien linglain
*/

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "mysh.h"

int		my_print(t_list *env)
{
  t_node	*current;

  current = env->start;
  while (current != NULL)
    {
      my_putstr(current->key);
      my_putchar('=');
      if (current->value != NULL)
	my_putstr(current->value);
      my_putchar('\n');
      current = current->next;
    }
  return (0);
}

int		check_key(t_list *env, char *key, char *value)
{
  t_node	*tmp;

  tmp = xmalloc(sizeof(t_node));
  tmp = env->start;
  while (tmp != NULL)
    {
      if (my_strcmp(tmp->key, key) == 0)
	{
	  tmp->value = value;
	  return (EXIT_SUCCESS);
	}
      tmp = tmp->next;
    }
  return (1);
}

int		my_add(t_list *env, char *key, char *value)
{
  t_node	*tmp;

  if (check_key(env, key, value) == 1)
    {
      tmp = xmalloc(sizeof(t_node));
      tmp->key =  my_strcpy(key);
      if (value != NULL)
	tmp->value = my_strcpy(value);
      if (value == NULL)
	tmp->value = NULL;
      if (env->start == NULL)
	env->start = tmp;
      else
	env->end->next = tmp;
      tmp->next = NULL;
      env->end = tmp;
      env->size++;
    }
  return (0);
}

int		init_env(t_list *envi, char **env)
{
  char		*key;
  char		*value;
  int		i;

  i = 0;
  envi->start = NULL;
  envi->end = NULL;
  envi->size = 0;
  while (env[i] != '\0')
    {
      key = get_key(env[i]);
      value = get_value(env[i]);
      my_add(envi, key, value);
      i++;
    }
  return (0);
}
